import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class SignalService {
  private socket?: WebSocket;
  private messageCallback?: (data: any) => void;

  constructor() {}

  // 初始化 WebSocket 连接
  connect() {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      return; // 避免重复连接
    }

    this.socket = new WebSocket(environment.apiUrl.replace(/^http/, 'ws') + '/signal');

    this.socket.onmessage = (event) => {
      if (this.messageCallback) {
        this.messageCallback(JSON.parse(event.data));
      }
    };

    this.socket.onclose = () => {
      console.log('WebSocket disconnected');
    };

    this.socket.onerror = (err) => {
      console.error('WebSocket error:', err);
    };
  }

  // 发送消息
  send(message: any) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket is not connected.');
    }
  }

  // 注册消息处理函数
  onMessage(callback: (data: any) => void) {
    this.messageCallback = callback;
  }

  // 关闭连接（离开房间时调用）
  leaveRoom() {
    if (this.socket) {
      this.socket.close();
      this.socket = undefined;
    }
  }
}
